import time as time_module  # 使用别名
from config_loader import load_config
from flask import request, jsonify
from cron_task.sever_chan_cron_task import alarms_task_today_server_chan
from service.handler import send_text_msg_qx, handle_set_alarm_qx, handle_alarms_query

# 加载配置
cfg = load_config("config.yml")
PREFIX_STR = cfg["PREFIX_STR"]
TIP_EXAMPLE = cfg["TIP_EXAMPLE"]

# 用户状态和时间戳
user_state = {}
user_timestamp = {}

# 定义白名单
whitelist = ['23909874137@chatroom', 'wxid_u8qw5xouz0cf22', 'wxid_83sin1vh46hf12']


# 千寻微信框架消息推送，当前版本千寻框架只推送抢购消息
def qx_wechat_message():
    # 获取参数
    data = request.json.get('data', {})
    wxid = request.json.get('wxid', '')
    msg_data = data.get('data', {})
    fromWxid = msg_data.get('fromWxid', '')
    # 白名单检查，检查发送人是否在白名单中
    if fromWxid not in whitelist:
        print('消息发送者不在白名单范围内......')
        return jsonify({"code": 200, "data": "sender not in whitelist"})
    # 获取请求中消息内容
    msg = msg_data.get('msg', '')
    print('叮！收到一条消息，发送人：{}，接收人：{}，消息内容：{}'.format(fromWxid, wxid, msg))
    # 检查是否超时
    if fromWxid in user_timestamp and time_module.time() - user_timestamp[fromWxid] > 600:
        user_state[fromWxid] = 'normal'
    #################################### 闹钟消息设置处理 ###########################################
    if msg == '闹钟':
        send_text_msg_qx(wxid, fromWxid, '💃💃请按下面格式设置💃💃' + chr(13) + PREFIX_STR + chr(13) + TIP_EXAMPLE)
        user_state[fromWxid] = 'waiting_for_alarm'
        user_timestamp[fromWxid] = time_module.time()
    elif user_state.get(fromWxid) == 'waiting_for_alarm' and msg != '退出':
        handle_set_alarm_qx(wxid, fromWxid, msg)
    elif user_state.get(fromWxid) == 'waiting_for_alarm' and msg == '退出':
        send_text_msg_qx(wxid, fromWxid, 'OKOK')
        user_state[fromWxid] = 'normal'
    #################################### 查询闹钟信息处理 ###########################################
    elif msg == '查询':  # 同时显示打卡和抢购数据
        handle_alarms_query(wxid, fromWxid, user_state)
        user_state[fromWxid] = 'waiting_for_id'  # 等待用户输入id状态
        user_timestamp[fromWxid] = time_module.time()
    elif user_state.get(fromWxid) == 'waiting_for_id' and msg == '退出':
        send_text_msg_qx(wxid, fromWxid, 'OKOK')
        user_state[fromWxid] = 'normal'
    ######################################## 签到打卡 ##############################################
    elif msg == '打卡':  # 只显示当天的打卡数据
        alarms_task_today_server_chan()
        user_timestamp[fromWxid] = time_module.time()

    return jsonify({"code": 200, "data": "result ok"})
